<template>
  <div class="anomaly-table-panel">
    <el-select class="Select" size="small" @change="refreshData" v-model="queryParams.timeParam" placeholder="请选择时间">
      <el-option 
        v-for="item in timeOptions" 
        :key="item.dateTimeString" 
        :label="item.formattedDateTime" 
        :value="item.dateTimeString" 
      />
    </el-select>
    <div class="panel-header">
      <h3>{{ title }}</h3>
      <!-- <div class="table-controls">
        <el-button size="small" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div> -->
    </div>
    <div class="panel-content">
      <el-table
        :data="anomalyData"
        style="width: 100%"
        size="small"
        :header-cell-style="{ background: 'rgba(0, 255, 0, 0.1)', color: '#00ff00' }"
        :cell-style="{ background: 'transparent', color: '#000' }"
        :row-style="{ background: 'transparent' }"
        height="320"
        @row-click="handleRowClick"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="xCoordinate" label="点位" width="160" align="center" >
          <template #default="{ row }">
            <span>
              {{ row.xCoordinate }},{{ row.yCoordinate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="windDirection" label="方向" min-width="120">
          <template #default="{ row }">
            <span :class="getWindDirectionClass(row.windDirection)">
              {{classifyWindDirections(row.windDirection) }}
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import {
  tableQuery,
  windDataPPI,
  getConfig,
  alarmRecord
} from '@/api/system/user'
const props = defineProps({
  title: {
    type: String,
    default: '设备异常记录'
  },
  deviceType: {
    type: String,
    default: 'A' // A 或 B
  }
})
const configForm = reactive({
  id: 0,
  max: null,
  min: null
})
// 时间选项数据
const timeOptions = ref([])
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: 'PPI',
  timeParam: undefined,
  ipaddr: undefined,
  userName: undefined,
  status: undefined,
  max: undefined,
  min: undefined,
})
const anomalyData = ref([])

// 定义emit事件
const emit = defineEmits(['row-click'])

// 处理行点击事件
const handleRowClick = (row) => {
  console.log('报警记录行点击:', row)
  // 向父组件发送行点击事件
  emit('row-click', row)
}

function classifyWindDirections(directions) {
  if (directions === null || directions === undefined || directions === '') {
    return '未知'
  }
  
  const angle = parseFloat(directions)
  if (isNaN(angle)) {
    return '未知'
  }
  
  // 将角度标准化到0-360度范围
  const normalizedAngle = ((angle % 360) + 360) % 360
  
  // 8个主要方向，每个方向45度
  if (normalizedAngle >= 337.5 || normalizedAngle < 22.5) {
    return '北'
  } else if (normalizedAngle >= 22.5 && normalizedAngle < 67.5) {
    return '东北'
  } else if (normalizedAngle >= 67.5 && normalizedAngle < 112.5) {
    return '东'
  } else if (normalizedAngle >= 112.5 && normalizedAngle < 157.5) {
    return '东南'
  } else if (normalizedAngle >= 157.5 && normalizedAngle < 202.5) {
    return '南'
  } else if (normalizedAngle >= 202.5 && normalizedAngle < 247.5) {
    return '西南'
  } else if (normalizedAngle >= 247.5 && normalizedAngle < 292.5) {
    return '西'
  } else if (normalizedAngle >= 292.5 && normalizedAngle < 337.5) {
    return '西北'
  }
  
  return '未知'
}

// 获取风向样式类
function getWindDirectionClass(directions) {
  if (directions === null || directions === undefined || directions === '') {
    return 'wind-unknown'
  }
  
  const angle = parseFloat(directions)
  if (isNaN(angle)) {
    return 'wind-unknown'
  }
  
  // 将角度标准化到0-360度范围
  const normalizedAngle = ((angle % 360) + 360) % 360
  
  // 8个主要方向，每个方向45度
  if (normalizedAngle >= 337.5 || normalizedAngle < 22.5) {
    return 'wind-north'
  } else if (normalizedAngle >= 22.5 && normalizedAngle < 67.5) {
    return 'wind-northeast'
  } else if (normalizedAngle >= 67.5 && normalizedAngle < 112.5) {
    return 'wind-east'
  } else if (normalizedAngle >= 112.5 && normalizedAngle < 157.5) {
    return 'wind-southeast'
  } else if (normalizedAngle >= 157.5 && normalizedAngle < 202.5) {
    return 'wind-south'
  } else if (normalizedAngle >= 202.5 && normalizedAngle < 247.5) {
    return 'wind-southwest'
  } else if (normalizedAngle >= 247.5 && normalizedAngle < 292.5) {
    return 'wind-west'
  } else if (normalizedAngle >= 292.5 && normalizedAngle < 337.5) {
    return 'wind-northwest'
  }
  
  return 'wind-unknown'
}

// 获取异常类型样式类
const getAnomalyClass = (content) => {
  const criticalAnomalies = ['通讯中断', '连接丢失', '系统故障', '硬件故障', '系统重启']
  const warningAnomalies = ['电压过高', '温度异常', '温度过高', '振动超标', '位置偏移']
  
  if (criticalAnomalies.includes(content)) {
    return 'anomaly-critical'
  } else if (warningAnomalies.includes(content)) {
    return 'anomaly-warning'
  } else {
    return 'anomaly-normal'
  }
}

/** 获取时间选项数据 */
async function getTimeOptions() {
    const response = await tableQuery(queryParams)
    if (response.code === 200) {
      timeOptions.value = response.data.result || []
      // 如果有数据且当前没有选择时间，自动选择第一个
      if (timeOptions.value.length > 0 && !queryParams.timeParam) {
        queryParams.timeParam = timeOptions.value[0].dateTimeString
        // 自动选择第一个时间后，获取对应的数据
        await getDataConfig()
      }
    }
   
}
async function getDataConfig() { 
  const response = await getConfig()
    if (response.code === 200) {
      // 填充配置表单数据
      Object.assign(configForm, response.data)
      refreshData()
    } else {
      proxy.$modal.msgError(response.msg || '获取配置失败')
    }
}
// 刷新数据
const refreshData = async () => {
  if (!queryParams.type || !queryParams.timeParam) {
    console.warn('请选择模式和时间')
    return
  }
  try {
    const params = {
      timeParam: queryParams.timeParam,
      pageNum: queryParams.pageNum,
      pageSize: 10000,
    }
    let response = await windDataPPI(params)
    anomalyData.value = response.data.result
  } catch (error) {
    proxy.$modal.msgError('获取数据失败')
  }

  
}

// 模拟实时添加异常记录
const addRandomAnomaly = () => {
  const today = new Date()
  const todayStr = `${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
  const timeStr = today.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  
  const deviceAAnomalies = [
    '电压过高', '温度异常', '通讯中断', '压力异常', '流量异常',
    '振动超标', '位置偏移', '连接丢失', '数据异常', '系统故障'
  ]
  
  const deviceBAnomalies = [
    '流量偏低', '振动超标', '位置偏移', '连接丢失', '温度过高',
    '压力不足', '通讯超时', '数据丢失', '系统重启', '硬件故障'
  ]
  
  const anomalyTypes = props.deviceType === 'A' ? deviceAAnomalies : deviceBAnomalies
  
  const newAnomaly = {
    serialNo: anomalyData.value.length > 0 ? Math.max(...anomalyData.value.map(item => item.serialNo)) + 1 : 1,
    time: `${todayStr} ${timeStr}`,
    content: anomalyTypes[Math.floor(Math.random() * anomalyTypes.length)]
  }
  
  anomalyData.value.unshift(newAnomaly)
  
  // 保持最多10条记录
  if (anomalyData.value.length > 10) {
    anomalyData.value = anomalyData.value.slice(0, 10)
  }
}

onMounted(async () => {
  await getTimeOptions()
})
</script>

<style scoped lang="scss">
.anomaly-table-panel {
  background: #ffffff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 8px;
  color: #333;
  min-width: 320px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  .Select{
    position: absolute;
    z-index: 1001;
    width: 160px;
    right: 12px;
    top: 11px;
  }
  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    padding: 8px 16px;
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
    border-radius: 8px;
    box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3);
    position: relative;
    overflow: hidden;
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
      pointer-events: none;
    }
    
    h3 {
      margin: 0;
      color: #ffffff;
      font-size: 12px;
      font-weight: 600;
      text-shadow: 0 1px 2px rgba(0,0,0,0.1);
      letter-spacing: 0.5px;
      position: relative;
      z-index: 1;
    }
    
    .table-controls {
      .el-button {
        background: #f8fafc;
        border-color: #d1d5db;
        color: #374151;
        
        &:hover {
          background: #e5e7eb;
          border-color: #9ca3af;
        }
      }
    }
  }
  
  .panel-content {
    :deep(.el-table) {
      background: transparent;
      
      .el-table__header-wrapper {
        background: #f8fafc;
      }
      
      .el-table__body-wrapper {
        background: transparent;
      }
      
      .el-table__row {
        background: transparent;
        height: 32px;
        
        &:hover {
          background: #f8fafc !important;
        }
      }
      
      .el-table__cell {
        border-color: #f3f4f6;
        padding: 4px 8px;
      }
      
      .el-table__header {
        th {
          background: #f8fafc;
          color: #374151;
          font-weight: 600;
          height: 32px;
          padding: 4px 8px;
        }
      }
      
      .el-table__body {
        td {
          color: #374151;
        }
      }
    }
  }
}

.anomaly-critical {
  color: #ef4444;
  font-weight: bold;
  background: #fef2f2;
  padding: 2px 6px;
  border-radius: 4px;
}

.anomaly-warning {
  color: #f59e0b;
  font-weight: bold;
  background: #fffbeb;
  padding: 2px 6px;
  border-radius: 4px;
}

.anomaly-normal {
  color: #10b981;
  font-weight: bold;
  background: #f0fdf4;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 风向样式 */
.wind-north {
  color: #1e40af;
  font-weight: bold;
  background: #dbeafe;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-northeast {
  color: #7c3aed;
  font-weight: bold;
  background: #ede9fe;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-east {
  color: #059669;
  font-weight: bold;
  background: #d1fae5;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-southeast {
  color: #dc2626;
  font-weight: bold;
  background: #fee2e2;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-south {
  color: #ea580c;
  font-weight: bold;
  background: #fed7aa;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-southwest {
  color: #ca8a04;
  font-weight: bold;
  background: #fef3c7;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-west {
  color: #0891b2;
  font-weight: bold;
  background: #cffafe;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-northwest {
  color: #be185d;
  font-weight: bold;
  background: #fce7f3;
  padding: 2px 6px;
  border-radius: 4px;
}

.wind-unknown {
  color: #6b7280;
  font-weight: bold;
  background: #f3f4f6;
  padding: 2px 6px;
  border-radius: 4px;
}
</style>